
var net = require('net')
var ACTIONS = require('./actions')
// const DataServer = require('./DataServer')
// var DataServer = require('./DataServer')

var ProxySocketsHold = new Map()
var ProxyPortServerHold = new Map()
const {Log} = require('./logger')


class ProxyPortServer{

    constructor(localPort, nodeName, nodePort, mainServer, dataServer){
        this.localPort = localPort
        this.nodeName = nodeName
        this.nodePort = nodePort
        this.proxyServer = null;
     
        this.sequence = 1;
        this.mainServer = mainServer
        this.dataServer = dataServer

        ProxyPortServerHold.set(this.getProxyServerID(), this)

    }

    getProxyServerID(){
        var id_str = "ppsid:"+ this.localPort +":"+this.nodeName + ":"+this.nodePort
        return id_str 
    }

    getConnectID(){
        var id_str = "cid:"+this.localPort+ ":"+this.nodeName+":"+this.nodePort+"-"+this.sequence
        this.sequence=this.sequence+1;
        return id_str
    }

    start(){
        // console.dir(DataServer)
        // DataServer.closeDataSocket("111")
        // DataServer.closeDataSocket("pppdddd")
        

        this.proxyServer = net.createServer((proxysocket)=>{

            Log.info("proxyserver connecting")
            Log.info("local %s, %s", proxysocket.localAddress, proxysocket.localPort)
            Log.info("remote %s,%s", proxysocket.remoteAddress, proxysocket.remotePort)
            var connection_id = this.getConnectID()
            ProxySocketsHold.set(connection_id, {socket:proxysocket, time:new Date(), status:'init'})
            
            proxysocket.connection_id = connection_id

            // 发送请求连接给node
            var action =new ACTIONS.REQLINK(connection_id, this.nodePort)
            let r =this.mainServer.send(this.nodeName, action)

            if( r  ==  false){
                proxysocket.destroy()
                return ;
            }

            proxysocket.on("close", (has_err)=>{
                Log.info('proxysocket close %s', proxysocket.connection_id)
                proxysocket.destroy() 
                ProxySocketsHold.delete(proxysocket.connection_id) 
             
                this.dataServer.closeDataSocket(proxysocket.connection_id)
            })

            proxysocket.on('error', (err)=>{
                Log.error("ProxySocket on error", err)
                proxysocket.destroy() 
                ProxySocketsHold.delete(proxysocket.connection_id)


                this.dataServer.closeDataSocket(proxysocket.connection_id)
            })
        })

        this.proxyServer.listen(this.localPort, ()=>{
                Log.info("proxyserver [%s] listen on %s", this.getProxyServerID(), this.localPort)
        })
    }

    close(cb){
        if(this.proxyServer){
            this.proxyServer.close(cb)
        }
    }
    
}

function getProxySocket(connnect_id){
    if(ProxySocketsHold.has(connnect_id)){
        return ProxySocketsHold.get(connnect_id)
    }
}

// 关闭带来端口
function closeProxySocket(connection_id){
    if(ProxySocketsHold.has(connection_id)){
        var ps = ProxySocketsHold.get(connection_id)
        ps.socket.destroy()
        ProxySocketsHold.delete(connection_id)
    }
}

function closeProxyPortServer(port){
    var pssid = null
    for(let k of ProxyPortServerHold.keys()){
       if( k.split(':')[1] == port ){
           pssid = k;
           break;
       }
    }

    if(pssid && ProxyPortServerHold.has(pssid)){
        var server = ProxyPortServerHold.get(pssid)
        server.close((err)=>{    
            ProxyPortServerHold.delete(pssid)
            Log.info("ProxyPortServer closed %s", pssid)
        })
        return pssid;
    }
}

// 废弃方法，已移动到WebServer.js中
function addProxyConfig(localPort, nodeName, nodePort){

    // var pssid = closeProxyPortServer(localPort)
    // if(pssid){
    //     setTimeout(() => {
    //         var  pps = new ProxyPortServer(localPort, nodeName, nodePort, MainServer.instance, DataServer)
    //         pps.start()
    //     }, 1000);
    // }else{
    //     var  pps = new ProxyPortServer(localPort, nodeName, nodePort, MainServer.instance, DataServer)
    //     pps.start()
    //     return pps.getProxyServerID()
    // }
}

function getAllProxyPortServerID(){
    var pidlist = new Array()
    for(let pid of ProxyPortServerHold.keys()){
        pidlist.push(pid)
    }
    return pidlist
}


ProxyPortServer.getProxySocket = getProxySocket
ProxyPortServer.closeProxySocket = closeProxySocket


ProxyPortServer.closeProxyPortServer = closeProxyPortServer
ProxyPortServer.addProxyConfig = addProxyConfig
ProxyPortServer.getAllProxyPortServerID = getAllProxyPortServerID

module.exports = ProxyPortServer
